import requests
import re
import json
import time
import jstopy
import peewee
from peewee import *

import requests

#获取后面要用到的cookie
def getCookie():
    cookies = {
        'JSESSIONID': '94E9CBB1E61032AD6D9C00BF6D9E309E',
    }
    headers = {
        'authority': 'b2c.csair.com',
        'accept': 'application/json, text/javascript, */*; q=0.01',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'cache-control': 'no-cache',
        # Already added when you pass json=
        # 'content-type': 'application/json',
        # 'cookie': 'JSESSIONID=94E9CBB1E61032AD6D9C00BF6D9E309E',
        'origin': 'https://b2c.csair.com',
        'pragma': 'no-cache',
        'referer': 'https://b2c.csair.com/B2C40/newTrips/static/main/page/booking/index.html?t=S&c1=CAN&c2=URC&d1=2022-10-15&at=1&ct=0&it=0&b1=CAN&b2=URC',
        'sec-ch-ua': '"Chromium";v="104", " Not A;Brand";v="99", "Google Chrome";v="104"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36',
        'x-requested-with': 'XMLHttpRequest',
    }

    params = {
        'type__1188': 'Yq0xyDn70QG=Yx05DIYYIFqWwR4RhD2ObD',
    }

    json_data = {
        'language': 'zh',
        'salesScene': 'AirLineSalse',
        'flightInfo': [
            {
                'segments': [
                    {
                        'index': 0,
                        'dep': 'CAN',
                        'arr': 'URC',
                        'depTime': '2022-10-20',
                    },
                ],
            },
        ],
        'businessType': 'COMMON',
        'depAirCode': [
            'CAN',
        ],
        'arrAirCode': [
            'URC',
        ],
    }

    response = requests.post('https://b2c.csair.com/portal/flight/queryairlinesales', params=params, cookies=cookies, headers=headers, json=json_data)
    return response.cookies.get_dict()
    # {'acw_tc': '7ce1c3a316654728823268632e6eea6c816cc7146c427f975fa9752378', 'cookiesession1': '678B286A45467361863B52436DAAD677', 'JSESSIONID': '4EADD13214A35D81A1C6ABE1AE1509D7'}

# 获取滑块参数n 暂时未破解  在collina.js 6863行 var n = e(1, o)处获取;
# 由于该函数还未解。就一次获取了多个值存入数据库备用
#@todo 该函数就是从数据库中取出该值，的操作
def getN():
    db = MySQLDatabase('test', user='root', passwd='root')
    class Nang(peewee.Model):
        param = CharField(10000)
        class Meta:
             database = db
    Nang.create_table()
    res=Nang.select().limit(1).get()
    res.delete_instance()
    return res.param



# 获取参数的一个请求
def getParam(t,n):
    headers = {
        'authority': 'cf.aliyun.com',
        'accept': '*/*',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'cache-control': 'no-cache',
        'pragma': 'no-cache',
        'referer': 'https://b2c.csair.com/',
        'sec-ch-ua': '"Chromium";v="104", " Not A;Brand";v="99", "Google Chrome";v="104"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'script',
        'sec-fetch-mode': 'no-cors',
        'sec-fetch-site': 'cross-site',
        'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36',
    }

    params = {
        'a': 'CF_APP_WAF',
        't': t,
        'n': n,
        'p': '{"key1":"code100","user":"default","aysnc":"1","ncSessionID":"5e701edbacde","umidToken":"T2gAaJ0JLahqnm9S30cmNRwOMTlinKKPyrf8-fQJ40TwatxPE1NLIZ24omBVYNCvsJc="}',
        'scene': 'register',
        'asyn': '0',
        'lang': 'cn',
        'v': '1083',
        'callback': 'jsonp_01926988216184573',
    }
    response = requests.get('https://cf.aliyun.com/nocaptcha/analyze.jsonp', params=params, headers=headers)
    text = response.text
    print(text)
    response =json.loads(re.search('jsonp_\d*\((.*)\)',text).groups()[0])['result']
    return  response


# @todo 获取'type__1188'参数，是调用js文件获取
def getTail(t,param):
    ss="https://b2c.csair.com/portal/flight/direct/query?u_atoken="+t+"&u_asession=" +param['csessionid']+"&u_asig="+param['value']+"&u_aref=123"+'{"depCity":"CAN","arrCity":"URC","flightDate":"20221020","adultNum":"1","childNum":"0","infantNum":"0","cabinOrder":"0","airLine":1,"flyType":0,"international":"0","action":"0","segType":"1","cache":0,"preUrl":"","tariffRules":[{"bigCustomer":"","domesticFlightGroup":"ZZTH02","isLowPriceRation":"0","flightLine":"CAN-URC"}],"isMember":"","businessType":"COMMON"}'
    tail =jstopy.execJs('main.js','tail',ss)
    return tail


# 为了获取重要cookie  acw_sc__v3
# 该请求禁止重定向
def getResult(cookies,t,param,tail):
    headers = {
        'authority': 'b2c.csair.com',
        'accept': 'application/json, text/javascript, */*; q=0.01',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'cache-control': 'no-cache',
        'origin': 'https://b2c.csair.com',
        'pragma': 'no-cache',
        'referer': 'https://b2c.csair.com/B2C40/newTrips/static/main/page/booking/index.html?t=S&c1=CAN&c2=URC&d1=2022-10-15&at=1&ct=0&it=0&b1=CAN&b2=URC',
        'sec-ch-ua': '"Chromium";v="104", " Not A;Brand";v="99", "Google Chrome";v="104"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36',
        'x-requested-with': 'XMLHttpRequest',
    }
    params = {
        'u_atoken': t,
        'u_asession':param['csessionid'],
        'u_asig': param['value'],
        'u_aref': '123',
        'type__1188': tail,
    }

    json_data = {
        'depCity': 'CAN',
        'arrCity': 'URC',
        'flightDate': '20221020',
        'adultNum': '1',
        'childNum': '0',
        'infantNum': '0',
        'cabinOrder': '0',
        'airLine': 1,
        'flyType': 0,
        'international': '0',
        'action': '0',
        'segType': '1',
        'cache': 0,
        'preUrl': '',
        'tariffRules': [
            {
                'bigCustomer': '',
                'domesticFlightGroup': 'ZZTH02',
                'isLowPriceRation': '0',
                'flightLine': 'CAN-URC',
            },
        ],
        'isMember': '',
        'businessType': 'COMMON',
    }
    response = requests.post('https://b2c.csair.com/portal/flight/direct/query', params=params, cookies=cookies, headers=headers, json=json_data,allow_redirects=False)
    print(response.cookies)
    return response.cookies.get_dict()


# 这一次请求和上一样，但是允许重定向。
# 这一次请求是获取数据，携带了上一次请求获取的cookie
def getData(cookies,t,param,tail):
    headers = {
        'authority': 'b2c.csair.com',
        'accept': 'application/json, text/javascript, */*; q=0.01',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'cache-control': 'no-cache',
        'origin': 'https://b2c.csair.com',
        'pragma': 'no-cache',
        'referer': 'https://b2c.csair.com/B2C40/newTrips/static/main/page/booking/index.html?t=S&c1=CAN&c2=URC&d1=2022-10-15&at=1&ct=0&it=0&b1=CAN&b2=URC',
        'sec-ch-ua': '"Chromium";v="104", " Not A;Brand";v="99", "Google Chrome";v="104"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36',
        'x-requested-with': 'XMLHttpRequest',
    }
    params = {
        'u_atoken': t,
        'u_asession':param['csessionid'],
        'u_asig': param['value'],
        'u_aref': '123',
        'type__1188': tail,
    }

    json_data = {
        'depCity': 'CAN',
        'arrCity': 'URC',
        'flightDate': '20221020',
        'adultNum': '1',
        'childNum': '0',
        'infantNum': '0',
        'cabinOrder': '0',
        'airLine': 1,
        'flyType': 0,
        'international': '0',
        'action': '0',
        'segType': '1',
        'cache': 0,
        'preUrl': '',
        'tariffRules': [
            {
                'bigCustomer': '',
                'domesticFlightGroup': 'ZZTH02',
                'isLowPriceRation': '0',
                'flightLine': 'CAN-URC',
            },
        ],
        'isMember': '',
        'businessType': 'COMMON',
    }
    response = requests.post('https://b2c.csair.com/portal/flight/direct/query', params=params, cookies=cookies, headers=headers, json=json_data)
    print(response.text)




# 最后执行一遍主函数
def main():
    cookies = getCookie()
    print(cookies)
    n= getN()
    print(n)
    # n="140#rAz4fSWDzzF2Qzo23i2b4pN8s775bGoA7NbJCG65BPKhzx0tz1Kyowyfp7qhJyPyWMU8OmSDQZoqlbzx1aCNtAZAzFc2n1aIlpTzzPzbVXlqlbdV4DGe1R6m1rwz7Cd8BLqLzYqUrZLu7BOoy5zi2ijPaF+MsSG+mgonziNbulrPQGfrsXfXnolbyFPXIZbuB9YAx2Nfcx5+sLfrvGSXnoEtyFP4pZbuZHIAx201cx5gyRfrbjFXnnBQyFFW7ibuRKYAxz2DcxQfb9fr+QTXnxwVybFwn5s/3XYwxzrEc561lGXrGV1BnU7xybF215rAjHkuxzlJrZfg6LQr+OrZdWCbvzWaVZrAc+cuxxwFrZAX7LQr0GQZdCH+vzFK0irAKaNuxoSrrZA3MRQrOzbZdFDQvzF8rirAXtquxLQqrZfWaRQr9E+ZdfWVvzWbKxrAX+auxxEIrxZwSLMrNk1FdzoHvFF1b5zf/YItxmN4rxFEMGMrnm2FdnYXvFWbNxzftGUtxKwSrxFXyLMrVjbFdx8+vFFKxxzfuqUtxLXLrxF709MrsxfFdoUzvFPacZzfn7UtxKslrxFkSRMrhEsFdDnIvQPkG52wxua/xLo7riXreGTrpXuPdblPvQPvI52w4+k/xmUCriRP7RTrNRsPdyN1vQPhp52wPYP/xoUYriX3IRTr4HXPdikCvQPczx2w4ODgxHYN3ooqUb+x2oa3V3gqzmsKr9EjmrvZrI7Zb71elkrRzUrI4pk3HYqg6J3DSj+19bIOAodIThX8/psmlj9kUGPVwtH6jkN7PQhqiEE2lC0HNSqg77COwHjhnXnZ/I6VxmdMIxKHxAw1ltgKegofx5yqjH2Fp8p22LfiO2wM/jvs3ufNzM5Az5+QjVYTLwP7DI0kGM4f5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JR8sD90xZA0mGNdhB0pbG7YJaXl7TqJv5b06JkRAb6JbE+ObgMjO4rVX3Yd4werZm7Lyzn0P5sqXG040IJI6khI20TkbBBAiK53i9fEcWbjbtMeEn2NIq28HXO19UuO1JE+cm8fb3sqrwjYF9F8wFICbXWpxvoCILnkr3GibmszsNLUmlCatZKVHEb0+naryIcq41s4JdQLje2NrF3LGxKen5XBmgXA87kE2jS06zjn2uPNR+41roE1ikTiovxtV/Hhq1iHUHt9Vdjlb6oWnC3iOxOgoSS3oV9d52Qa7aDMe4uVxuhm12+ylfTix7/a+479HDiQhJ96k9wvPIDt/htqp7maASPftJrWiTqVO8mC3Q7zhT55AOapJHI6HKBwVu2CVi3Ap9Sz7tuTKmkcuAZtOKuiXBa3WpvNaUi7GybJhBHnu5FgpUe/VEYhzV24deARfLVtKW60zpyyhwGfwr0LcLCn5"
    t = "0b72f618-4c1-4aba-9a78-f"+str(int(time.time()*1000))+'ba'
    param =getParam(t,n)
    print(param)
    tail =getTail(t,param)
    print(tail)
    acw_sc__v3=getResult(cookies,t,param,tail)
    cookies['acw_sc__v3']= acw_sc__v3['acw_sc__v3']
    getData(cookies,t,param,tail)

main()

































